package com.huarui.partner.service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.huarui.company.model.Company;
import com.huarui.company.service.CompanyService;
import com.huarui.notice.INoticeService;
import com.huarui.notice.Notice;
import com.huarui.notice.NoticeDealer;
import com.huarui.partner.model.Partner;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.PinyinToolkit;

public class AddPartnerNoticeDealer implements NoticeDealer {

	private Logger logger = Logger.getLogger(AddPartnerNoticeDealer.class);

	@Override
	public String aboutJsModuleId() {

		return "acceptAddPartner";
	}

	private PartnerService partnerService;
	private CompanyService companyService;
	private INoticeService noticeService;

	public void setNoticeService(INoticeService noticeService) {
		this.noticeService = noticeService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public void setPartnerService(PartnerService partnerService) {
		this.partnerService = partnerService;
	}

	@Override
	public boolean deal(Notice notice, boolean dealed,Map<String, String[]> params, Map<String, Object> resultHolder) {

		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		
		Integer ownerId = sessionMessage.getCompanyId();
		
		Integer senderId = sessionMessage.getUserId();
		
		JSONObject jsonObject = JSONObject.fromObject(notice.getJsArgs());
		
		String relation = jsonObject.getString("relation");
		
		Integer companyId = jsonObject.getInt("inviteCompanyId");

		
		Integer otherPartnerId = jsonObject.getInt("partnerId");	
		
		String acceptCompanyName = sessionMessage.getCompanyName();
		
		if (companyId.equals(ownerId)) {

			resultHolder.put("failure", "isSelf");

			return false;
	  }
		try {

			if (dealed) {
				boolean b=agreenDeal(resultHolder,params,ownerId,companyId,relation,acceptCompanyName,senderId,otherPartnerId);

				return b;
			} else {

				notAgreenDeal(params,ownerId,acceptCompanyName,senderId,companyId);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultHolder.put("failure", e.getMessage());
			logger.debug(e.getMessage());
			return false;
		}

		return true;
	}
	
	
	@SuppressWarnings("unchecked")
	private boolean agreenDeal( Map<String, Object> resultHolder,Map<String, String[]> params,Integer ownerId ,Integer companyId,String relation,String acceptCompanyName,Integer senderId,Integer otherPartnerId) throws IllegalAccessException, InvocationTargetException{

		Integer ownerPartnerId=null;
		String[] paramsArray = params.get("ownerPartnerId");
		
		if(paramsArray.length!=0){
			if(StringUtils.isNotBlank(paramsArray[0])){
				
		      ownerPartnerId =Integer.valueOf(paramsArray[0]);
		      
			}
		}
			
		Company company= (Company) companyService.getById(companyId);
		Company ownerCompany = (Company) companyService.getById(ownerId);
			

		Notice notice1 = new Notice();

		String jsArgs = "{acceptCompanyId:" + ownerId
				+ "acceptCompanyName:'" + acceptCompanyName + "'}";

		notice1.setNoticeType(1);
		notice1.setJsArgs(jsArgs);
		notice1.setJsModuleId("");
		notice1.setSenderId(senderId);
		notice1.setReceiverId(companyId);
		notice1.setReceiveType(1);
		notice1.setTitle(acceptCompanyName + "已接受您的邀请");

		if ("0".equals(relation)) {

			notice1.setContent(acceptCompanyName + "已接受您的邀请,并加您为他的卖家");

		} else if ("1".equals(relation)) {

			notice1.setContent(acceptCompanyName + "已接受您的邀请,并加您为他的买家");
		} else {

			notice1.setContent(acceptCompanyName
					+ "已接受您的邀请,并加您为他的买家和卖家");

		}
		Partner partner=null;
		Partner partner1=null;
		Partner pn=null;
		Partner pn1=null;
		//对于发出请求的公司来说,是否有这个未认证的往来单位信息
		if(otherPartnerId==0){
			
			
            //查看发出请求的公司,是否有已删除的往来单位信息

			Map mm = new HashMap();
			mm.put("ownerId", companyId);
			mm.put("companyId", ownerId);
			mm.put("isDelete", 1);

			pn1 = partnerService.findPartnerByOwnerId(mm);
					
			
			//如果发出请求的公司没有的话,就创建一个往来单位信息
			if(pn1==null){			
				 
			   if(StringUtils.isNotBlank(ownerCompany.getTaxCode())){					 
				 HashMap map = new HashMap(); 
			     map.put("ownerId",companyId);     		     
			     map.put("taxCode", ownerCompany.getTaxCode());
			     pn1= partnerService.getPartnerByTaxCode(map);
			     
			 }

				if(pn1==null){						
					
				    partner1 = new Partner();
					BeanUtils.copyProperties(partner1, ownerCompany);
					partner1.setId(null);
					partner1.setOwnerId(companyId);
					partner1.setCompanyId(ownerId);
					partner1.setGrantPrivacy(1);
					partner1.setRelation(relation);
		
				}else{
					copyPartner(ownerCompany,pn1,relation);						
				}
				
			//如果发出请求的公司已有该往来单位信息的话,就恢复该往来单位信息
			}else{
				
				pn1.setIsDelete(0);
				pn1.setRelation(relation);
				
	   }
	
	}else{
			     //发送请求的公司已经存在了一个非认证往来单位的信息

            	  pn1 = (Partner)partnerService.getById(otherPartnerId);
            	  pn1=copyPartner(ownerCompany,pn1,relation);

      
	}
		
		Partner pr=null;
		
  	    if(ownerPartnerId==null){
		  
  	    	if(StringUtils.isNotBlank(company.getTaxCode())){    		
  		       HashMap map = new HashMap();
  		       map.put("ownerId",ownerId);
  		       map.put("taxCode", company.getTaxCode());
  		       pr= partnerService.getPartnerByTaxCode(map);
  	    	}
  	    	

	       //根据公司税号去查,如果有这条记录,而不选择的话 就报错
	       if(pr!=null){
	    	   
	    	   resultHolder.put("failure","you are must choose one");
	    	   
	    	   return false;
	     }
	       //根据税号去查没有这条记录的情况
			  		    	   
	    //再根据公司的法人身份证去查,经过个人认证的公司,是只能根据法人省份证去确定的,这样可以确定是否有过这条往来单位信息	   
			   
				Map m = new HashMap();
				m.put("ownerId", ownerId);
				m.put("companyId", companyId);
				m.put("isDelete", 1);

				pn = partnerService.findPartnerByOwnerId(m);
		       //确定接收请求的公司从来未加过该往来单位信息,那么就新建一个客户信息
				if(pn==null){
					
					   partner = new Partner();
					   BeanUtils.copyProperties(partner, company);
					   partner.setId(null);
					   partner.setOwnerId(ownerId);
			           partner.setCompanyId(companyId);
			           partner.setRelation("");
					   partner.setGrantPrivacy(1);
					   partner=getWithRelation(relation,partner);		
				//查处曾经有过该往来单位,但确删除了,恢复该往来单位的信息
				}else{
					
					pn.setIsDelete(0);
					pn=getWithRelation(relation,pn);
					
					
				} 		  
		  
 }else{
	      //接收消息的公司根据税号或者法人身份证号查出的客户    	  
	      pn =(Partner)partnerService.getById(ownerPartnerId);
	      pn.setCompanyId(companyId);
	      pn.setIsDelete(0);
	      pn.setGrantPrivacy(1);
	      pn=getWithRelation(relation,pn);

 }

		
		
		//如果发送消息的公司没有该往来单位信息同时接收消息的公司也没有该往来单位信息 
		if(pn==null && pn1==null){							

			partnerService.createTogether(partner, partner1,notice1);
			
	 }
		//如果发送消息的公司没有该往来单位信息同时接收消息的公司有该往来单位信息 
		else if(pn==null&&pn1!=null){
		   
	    	partnerService.updatePn1(partner, pn1, notice1);						   
		   
	 }
	    //如果发送消息的公司有该往来单位信息同时接收消息的公司也有该往来单位信息 
		else if(pn!=null&&pn1!=null){
	    					    	
	    	partnerService.updateTogether(pn, pn1, notice1);
	  }
	  //如果发送消息的公司有该往来单位信息同时接收消息的公司没有该往来单位信息 
		else if(pn!=null&&pn1==null){
	    	
	    	partnerService.updatePn(pn, partner1,notice1);
	    	
	 }
	
	    
	    return true;
	}
          private void notAgreenDeal(Map<String, String[]> params,Integer ownerId,String acceptCompanyName,Integer senderId,Integer companyId){
	
				String[] paramsArray = params.get("remark");
				Notice notice2 = new Notice();

				String jsArgs = "{acceptCompanyId:" + ownerId + "reason:"
						+ paramsArray[0] + "acceptCompanyName:"
						+ acceptCompanyName + "}";

				notice2.setNoticeType(1);
				notice2.setJsArgs(jsArgs);
				notice2.setJsModuleId("");
				notice2.setSenderId(senderId);
				notice2.setReceiverId(companyId);
				notice2.setReceiveType(1);
				notice2.setTitle(acceptCompanyName + "拒绝了您的邀请");

				if (StringUtils.isBlank(paramsArray[0])) {

					notice2.setContent(acceptCompanyName + "拒绝了您的邀请");

				} else {

					notice2.setContent(acceptCompanyName + "拒绝了您的邀请,理由是:"
							+ paramsArray[0]);
				}

				noticeService.send(notice2, 24);
	
   }
          
          private Partner getWithRelation(String relation,Partner partner){
        	  
        	   
        		if ("0".equals(relation)) {

        			if("0".equals(partner.getRelation())){
        				
        				partner.setRelation("2");
        				
        			}else{
        			
       				    partner.setRelation("1");
        			
        			}

       			} else if ("1".equals(relation)) {

                       if("1".equals(partner.getRelation())){
        				
        				partner.setRelation("2");
        				
        			}else{
        				
       				    partner.setRelation("0");
       				
        		  }
       			} else {

       				partner.setRelation("2");
       			} 
        		
        		return partner;
        	  
          }
          
          
          private Partner copyPartner(Company ownerCompany , Partner pn1,String relation){
        	     	      	  
        	  pn1.setBankCode(ownerCompany.getBankCode());
              pn1.setName(ownerCompany.getName());
              pn1.setNameEn(ownerCompany.getNameEn());
              pn1.setPyCode(PinyinToolkit.cn2FirstSpell(pn1.getName()));
              pn1.setAreaId(ownerCompany.getAreaId());
              pn1.setContactor(ownerCompany.getContactor());
              pn1.setBankName(ownerCompany.getBankName());
              pn1.setCompanyId(ownerCompany.getId());
              pn1.setEmail(ownerCompany.getEmail());
              pn1.setFax(ownerCompany.getFax());
              pn1.setInvoicAddress(ownerCompany.getInvoicAddress());
              pn1.setAddress(ownerCompany.getAddress());
              pn1.setMsn(ownerCompany.getMsn());
              pn1.setQq(ownerCompany.getQq());
              pn1.setCity(ownerCompany.getCity());
              pn1.setProvince(ownerCompany.getProvince());
              pn1.setSimpleName(ownerCompany.getSimpleName());
              pn1.setTel(ownerCompany.getTel());
              pn1.setCode(ownerCompany.getCode());
              pn1.setContactorIdentityCode(ownerCompany.getContactorIdentityCode());
              pn1.setWeb(ownerCompany.getWeb());
			  pn1.setIsDelete(0);
			  pn1.setGrantPrivacy(1);
			  pn1.setRelation(relation);			
			  
			  return pn1;
  	  
          }
         
}
